<?php

class Usergroup extends ActiveRecordBase
{
	public $group_privileges;

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return '{{usergroups}}';
    }

	public function relations() {
		return array(
			'users' => array(self::MANY_MANY, 'User', '{{usergroup_links}}(usergroup_id, user_id)'),
			'privileges' => array(self::MANY_MANY, 'Privilege', '{{usergroup_privileges}}(usergroup_id, privilege)'),
		);
	}

	public function rules()
	{
		return array(
			array('usergroup, status', 'required'),
		);
	}

	/**
	 * Declares attribute labels.
	 */
	public function attributeLabels()
	{
		return array(
			'usergroup' => t('Usergroup'),
			'status' => t('Status'),
		);
	}

	function savePrivileges($privileges) {
		$sql = "REPLACE INTO {{usergroup_privileges}} VALUES ";
		$values = array();
		foreach ($privileges as $privilege => $ignore) {
			$values[] = sprintf("(%d, '%s')", $this->usergroup_id, $privilege);
		}
		$sql .= implode(',', $values);

		// first delete
		app()->db->createCommand()->delete("{{usergroup_privileges}}", "usergroup_id=:usergroup_id", array(':usergroup_id' => $this->usergroup_id));
		// then insert
		app()->db->createCommand($sql)->execute();
	}

	public function getUsergroup($id) {
		$model = $this->findByPk($id);

//		$group_privileges = app()->db->createCommand()
//					->select('privilege')
//					->from('{{usergroup_privileges}}')
//					->where('usergroup_id=:usergroup_id', array(':usergroup_id' => $id))
//					->queryColumn();
		$group_privileges = self::getGroupPrivileges($id);

		$model->group_privileges = $group_privileges;

		return $model;
	}

	public static function getGroupPrivileges($usergroup_id) {
		$privileges = app()->db->createCommand()
					->select('privilege')
					->from('{{usergroup_privileges}}')
					->where('usergroup_id=:usergroup_id', array(':usergroup_id' => $usergroup_id))
					->queryColumn();

		return $privileges;
	}
}
?>